<?php
declare(strict_types = 1);

namespace app\api\controller;

use app\common\controller\ApiBase;
use app\common\model\UserApi;
use app\common\wormview\AddEditList;
use app\facade\hook\Common;
use app\facade\wormview\Upload;
use think\exception\ValidateException;
use weixin\WxBase;

class Pay extends ApiBase
{
    use AddEditList;
    protected $PayDataModel;
    protected $PayCheModel;
    protected $PayLinshiModel;
    protected $types;
    protected function initialize(){
        parent::initialize(); // TODO: Change the autogenerated stub
        if(!$this->isLogin()){
            $this->result('','10000','请登录');
        }
        $mdodel = "app\\common\\model\\PayBase";
        $PayDataModel = "app\\common\\model\\PayData";
        $PayLinshiModel = "app\\common\\model\\PayLinshi";
        $PayCheModel = "app\\common\\model\\PayChe";
        $this->model = new $mdodel;
        $this->PayDataModel = new $PayDataModel;
        $this->PayLinshiModel = new $PayLinshiModel;
        $this->PayCheModel = new $PayCheModel;
        $this->validate = "app\\common\\validate\\PayBase";
    }
    protected function getMap()
    {
        $map = [
            'uid' => $this->wormuser['uid'],
            'oid' => empty($this->getdata['oid']) ? '' : $this->getdata['oid'],
            'payclass' => empty($this->getdata['payclass']) ? '' : $this->getdata['payclass'],
            'status' => !isset($this->getdata['status']) ? 'a' : $this->getdata['status'],
        ];
        return $map;
    }
    public function save()
    {
        if(!$this->request->isPost()){
            $this->result('','0','非法访问');
        }
        $data = Common::data_trim(input('post.'));
        $_paytype = empty($data['_paytype']) ? '0' : $data['_paytype'];
        if($this->wormuser['uid'] != $data['uid']){
            $this->result('','0','非法访问');
        }
        try {
            validate($this->validate)->scene(empty($data['oid']) ? "box" : "boxedit")->check($data);
        }catch (ValidateException $e){
            $this->result('','0',$e->getError());
        }
        foreach ($data['shoplist'] as $k => $v){
            try {
                validate($this->validate)->scene(empty($data['oid']) ? "add" : "edit")->check($v);
            }catch (ValidateException $e){
                $this->result('','0',$e->getError());
            }
        }
        //  获取订单号
        $oid = !empty($data['oid']) ? $data['oid'] : "WR".date('YmdHis',time()).get_range(8);
        //  打包订单信息
        $shoplist = $this->CountList($data,$oid);
        $_shoplist = $shoplist['shoplist'];
        $_stock = $shoplist['stock'];
        //  计算总金额
        $_money = array_sum(array_column($_shoplist,'money_zon'));
        //  查询优惠券
        $_del = 0;
        if(!empty($data['cuid'])){
            $cuModel = "app\\common\\model\\quan\\CouponUser";
            $cuModel = new $cuModel;
            $countpay = $cuModel->CountPay($_money,$data['cuid'],$_shoplist,$this->wormuser['uid']);
            if($countpay['code'] == '0'){
                $this->result('','0',$countpay['msg']);
            }
            $_del = (int) ($countpay['data'] * 100);
        }
        $rModel = new \app\common\model\UserAddress();
        $useraddress = $rModel->getOne($data['address_id']);
        $paymoney_zk = $_money - $_del;
        $add = [
            'oid' => $oid,
            'cuid' => empty($data['cuid']) ? '0' : $data['cuid'],
            'uid' => $this->wormuser['uid'],
            'payclass' => empty($data['payclass']) ? '0' : $data['payclass'],
            'paymoney' => $_money,
            'paymoney_zk' => $paymoney_zk > '0' ? $paymoney_zk : '0',
            'express_money' => empty($this->webdb['express_money']) ? '0' : $this->webdb['express_money'] * 100,
            'pay_name' => $useraddress['uname'],
            'pay_phone' => $useraddress['uphone'],
            'pay_zonecode' => $useraddress['zoneid'],
            'pay_cartid' => $useraddress['cartid'],
            'pay_address' => $useraddress['uaddress'],
            'cont' => empty($data['cont']) ? '' : json_encode($data['cont'],JSON_UNESCAPED_UNICODE),
            'addtime' => time(),
            'paytime' => empty($_money) ? time() : '0',
            'status' => empty($_money) ? '1' : '0',
            'del_time' => '0',
        ];
        if($add = $this->model->setOne($add)){
            if($paydata = $this->PayDataModel->setList($_shoplist,$oid)){
                if($_paytype == '1'){
                    $_shoplist = $this->PayCheModel->editList($shoplist,$this->wormuser['uid'],true);
                    $_id = $_shoplist['id'];
                    unset($_shoplist['id']);
                    $_data = [
                        'id' => $_id,
                        'uid' => $this->wormuser['uid'],
                        'cont' => json_encode($_shoplist,JSON_UNESCAPED_UNICODE),
                        'addtime' => time()
                    ];
                    $this->PayCheModel->setOne($_data);
                }
                //  检测是否使用了优惠的确如此
                if(!empty($add['cuid'])){
                    $cuModel->whereId($add['cuid'])->update(['oid' => $add['oid'],'status' => '1']);
                }
                $this->result($add,'1','添加订单成功');
            }else{
                $this->model->whereOid($oid)->delete();
            }
        }
        $this->result('','0','添加订单失败');
    }
    public function payWx($oid){
        $listdb = $this->model->getOne($oid);
        if($listdb['status'] == '1' && $listdb['paytime'] > '0'){
            cache("oid{$oid}",null);
            $this->result('','0','订单已支付');
        }
        $listdb['lsoid'] = "LS".date('YmdHis',time()).get_range(8);
        $listdb['title'] = "支付订单: {$listdb['oid']}";
        $_paymodel = empty($listdb['paymoney_zk']) ? $listdb['paymoney'] : $listdb['paymoney_zk'];
        $listdb['payzmoney'] = ($_paymodel + $listdb['express_money']) * 100;
        $this->types = $this->is_weixin();
        if(!empty($this->getdata['logintype']) && $this->getdata['logintype'] == 'wx-mp'){
            $this->types = 'wx-mp';
        }
        if($this->is_weixin() == 'h5'){
            $this->result('','0','请在微信客户端打开');
        }
        $wxModel = new WxBase();
        $apiModel = new UserApi();
        $user_api = $apiModel->getList(['uid' => $this->wormuser['uid']]);
        if($this->types == 'wx-mp'){
            $user_api = Common::del_file($user_api,'type','wx-mp');
        }else{
            $user_api = Common::del_file($user_api,'type','wx');
        }
        if(empty($user_api['0'])){
            $this->result('','0','请先绑定微信');
        }
        $listdb['openid'] = $user_api['0']['openid'];
        $_wx_appid = $this->types == 'wx-mp' ? $this->webdb['wx_mp_appid'] : $this->webdb['wx_appid'];
        $_wx_appsecret = $this->types == 'wx-mp' ? $this->webdb['wx_mp_appsecret'] : $this->webdb['wx_appsecret'];
        $_wxtoken = $wxModel->get_base_token($_wx_appid,$_wx_appsecret);
        $_wxjsapi = $wxModel->get_jsapi($_wxtoken);
        $_wxjsapi = $wxModel->get_jssing($_wxjsapi,url("/api/wxpay-{$listdb['oid']}")->domain(true)->build());
        if($_wxjsapi == false){
            $this->result('','0','唤起微信支付失败，请重试！');
        }
        $_paydata = $this->types == 'wx-mp' ? $wxModel->pay_add($this->webdb,$listdb,'wx-mp') : $wxModel->pay_add($this->webdb,$listdb);
        if($_paydata['return_code'] == 'SUCCESS' && $_paydata['return_msg'] == 'OK' && $_paydata['result_code'] == 'SUCCESS'){
            $listdb['pay_data'] = $wxModel->get_play($this->webdb,$_paydata);
        }else{
            $this->result('','0','唤起微信支付失败，请重试！');
        }
        $listdb['wx_config'] = $_wxjsapi;
        $addLsoid = [
            'lsoid' => $listdb['lsoid'],
            'oid' => $listdb['oid'],
            'addfile' => 'lsoid',
        ];
        $res = $this->PayLinshiModel->setOne($addLsoid);
        if($res['code'] == '0'){
            $this->result('','0','唤起支付信息失败');
        }
        $listdb = Upload::editadd($listdb,false);
        return $this->viewApiRead($listdb);
    }
    public function read($oid)
    {
        $getlist = $this->model->getOne($oid);
        if($getlist['uid'] != $this->wormuser['uid']){
            $this->result('','0','非法访问');
        }
        return $this->viewApiRead($getlist);
    }

    public function savecont(){
        if(!$this->request->isPost()){
            $this->result('','0','非法访问');
        }
        $data = Common::data_trim(input('post.'));
        if(empty($data['oid'])){
            $this->result('','0','非法访问');
        }
        $_old = $this->model->getOne($data['oid']);
        if($_old['uid'] != $this->wormuser['uid']){
            $this->result('','0','非法访问');
        }
        $add = [
            'oid' => $data['oid'],
            'cont' => json_encode($data['cont'],JSON_UNESCAPED_UNICODE),
        ];
        if($this->model->whereOid($add['oid'])->update(['cont' => $add['cont']])){
            $this->result('','1','保存成功');
        }
        $this->result('','0','保存失败');
    }
    public function savefucont(){
        if(!$this->request->isPost()){
            $this->result('','0','非法访问');
        }
        $data = Common::data_trim(input('post.'));
        if(empty($data['id']) || empty($data['oid'])){
            $this->result('','0','非法访问');
        }
        $_old = $this->model->getOne($data['oid']);
        if($_old['uid'] != $this->wormuser['uid']){
            $this->result('','0','非法访问');
        }
        $shoplist = $_old['shoplist'];
        $shoplist = Common::del_file($shoplist,'id',$data['id']);
        if(empty($shoplist['0'])){
            $this->result('','0','非法访问');
        }
        $shoplist = $shoplist['0'];
        foreach ($shoplist['fu_cont'] as $k => $v){
            foreach ($data['fu_cont'] as $k1 => $v1){
                if($v['title'] == $v1['title']){
                    $v['value'] = $v1['value'];
                    $shoplist['fu_cont'][$k] = $v;
                    unset($data['fu_cont'][$k1]);
                }
                continue;
            }
        }
        if(!empty($data['fu_cont'])){
            $shoplist['fu_cont'] = array_merge($shoplist['fu_cont'],$data['fu_cont']);
        }
        $add = [
            'id' => $data['id'],
            'fu_cont' => json_encode($shoplist['fu_cont'],JSON_UNESCAPED_UNICODE),
        ];
        if($paydata = $this->PayDataModel->setOne($add)){
            $this->result('','1','保存成功');
        }
        $this->result('','0','保存失败');
    }
    /**
     * 价格计算
     */
    public function prophet(){
        if(!$this->request->isPost()){
            $this->result('','0','非法访问');
        }
        $data = Common::data_trim(input('post.'));
        //  打包订单信息
        $shoplist = $this->CountList($data);
        $_shoplist = $shoplist['shoplist'];
        //  计算总金额
        $res['money'] = array_sum(array_column($_shoplist,'money_zon'));
        //  查询优惠券
        $_del = 0;
        if(!empty($data['cuid'])){
            $cuModel = "app\\common\\model\\quan\\CouponUser";
            $cuModel = new $cuModel;
            $countpay = $cuModel->CountPay($res['money'],$data['cuid'],$_shoplist,$this->wormuser['uid']);
            if($countpay['code'] == '0'){
                $this->result('','0',$countpay['msg']);
            }
            $_del = (int) ($countpay['data'] * 100);
        }
        $res['money_zk'] = $res['money'] - $_del;
        $this->result($res,'1','计算成功');
    }

    protected function CountList($data,$oid = ''){
        $shoplist = [];
        foreach ($data['shoplist'] as $k => $v){
            $v['chinacode'] = empty($data['chinacode']) ? '' : $data['chinacode'];
            $v['oid'] = $oid;
            $v = $this->model->getArticle($v,$this->wormuser);
            $shoplist[] = $v;
        }
        $_shoplist = array_column($shoplist,'shoplist');
        $_eshop = [];
        foreach ($_shoplist as $k => $v){
            $_eshop = array_merge($_eshop,$v);
        }
        $_shoplist = $_eshop;
        $_stock = array_column($shoplist,'stock');
        $_stock = Common::del_null($_stock);
        $_eshop = [];
        foreach ($_stock as $k => $v){
            $_eshop = array_merge($_eshop,$v);
        }
        $_stock = $_eshop;
        $shoplist = [
            'shoplist' => $_shoplist,
            'stock' => $_stock,
        ];
        return $shoplist;
    }
}
